package com.Monica.pojo;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.math.BigDecimal;
import java.util.List;

public class Dom4jTest {
    @Test
    public void test1() throws Exception {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read("src/books.xml");
        System.out.println(document);
    }
    /*
    读取books.xml文件生成book类
     */
    @Test
    public void test2() throws Exception {
        //1.读取books.xml文件
        SAXReader reader = new SAXReader();
        Document document = reader.read("src/books.xml");
        //2.通过document对象获取根元素
        Element rootElement = document.getRootElement();
        //3.通过根元素获取book标签对象
        List<Element> books = rootElement.elements("book");
        //4.遍历，处理每个book标签转换为Book类
        for (Element book : books){
            //System.out.println(book.asXML());
            //asXML()把标签对象转换为标签字符串
            Element nameElement = book.element("name");
            //getText()获得标签中的文本内容
            String nameText = nameElement.getText();
            //elementText()直接获得指定标签名的文本内容
            String priceText = book.elementText("price");
            String authorText = book.elementText("author");

            String snValue = book.attributeValue("sn");

            System.out.println(new Book(snValue,nameText,Double.parseDouble(priceText),authorText));

        }
    }
}
